package com.atguigu.tingshu.user.api;

import com.atguigu.tingshu.common.execption.GuiguException;
import com.atguigu.tingshu.common.login.annotation.TingshuLogin;
import com.atguigu.tingshu.common.result.Result;
import com.atguigu.tingshu.common.result.ResultCodeEnum;
import com.atguigu.tingshu.common.util.AuthContextHolder;
import com.atguigu.tingshu.model.user.UserInfo;
import com.atguigu.tingshu.user.service.UserInfoService;
import com.atguigu.tingshu.vo.user.UserInfoVo;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

@Tag(name = "微信授权登录接口")
@RestController
@RequestMapping("/api/user/wxLogin")
@Slf4j
public class WxLoginApiController {

    @Autowired
    private UserInfoService userInfoService;

    //Request URL: http://localhost:8500/api/user/wxLogin/wxLogin/0c3O9l1001qgTT19I3100HpXiV1O9l1L
    @GetMapping("/wxLogin/{code}")
    @Operation(summary = "微信小程序登录")
    public Result wxLogin(@PathVariable(value = "code") String code) {
        Map<String, Object> map = userInfoService.wxLogin(code);
        return Result.ok(map);
    }

    // Request URL: http://192.168.200.1:8500/api/user/wxLogin/getUserInfo
    @GetMapping("/getUserInfo")
    @Operation(summary = "获取用户信息")
    @TingshuLogin
    public Result getUserInfo() {
        // 从ThreadLocal中获取用户id
        Long userId = AuthContextHolder.getUserId();
        UserInfoVo userInfoVo = userInfoService.getUserInfo(userId);
        return Result.ok(userInfoVo);
    }

    @GetMapping("/refreshToken/getNewAccessToken")
    @Operation(summary = "获取新令牌")
    public Result getNewAccessToken() {
        Map<String, Object> map = userInfoService.getNewAccessToken();
        String flag = (String) map.get("1");
        if (map != null && StringUtils.isEmpty(flag)) {
            return Result.build(null, ResultCodeEnum.LOGIN_AUTH);
        }
        return Result.ok(map);
    }

    //Request URL: http://localhost:8500/api/user/wxLogin/updateUser
    @PostMapping("/updateUser")
    @TingshuLogin
    @Operation(summary = "更新用户信息")
    public Result updateUser(@RequestBody UserInfoVo userInfoVo) {
        userInfoService.updateUser(userInfoVo);
        return Result.ok();
    }


}
